import Vue from 'vue'
import Vuex from 'vuex'
import router, {authRouter, createRouters, commonRouter} from './router'
import {login, fetchUserInfo} from './requestData'

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        token: sessionStorage.getItem("token") != null ? sessionStorage.getItem("token") : [],
        UserInfo: {},
    },
    mutations: {
        // 清除token
        clearToken(state) {
            state.token = [];
            sessionStorage.removeItem("token")
        },
        // 设置用户，及token
        setUserInfo: function (state, user) {
            // 更新状态
            state.UserInfo = user;
            state.token = user.token;
            // 设置token
            sessionStorage.setItem("token", user.token);
            // 生成路由
            let routers = createRouters(state.UserInfo, authRouter);
            console.log(JSON.stringify(routers));
            // 在这里添加路由，防止数据更新数据延迟
            router.addRoutes(routers);

            // 拼接所有路由，显示菜单
            let concatRouter = commonRouter.concat(routers);
            //添加到本地
            sessionStorage.setItem("dyRouter", JSON.stringify(concatRouter));
        }
    },
    actions: {
        // 获取用户信息
        async getUserInfo(ctx, token) {
            return fetchUserInfo(token).then((res) => {
                // 获取用户成功
                if (res.code === 200) {
                    ctx.commit('setUserInfo', res.data.userInfo)
                }
                return res
            })
        },
        // 登陆
        async login(ctx, userFrom) {
            return login(userFrom).then((res) => {
                // 判断是否成功，防止获取不到data
                if (res.code === 200) {
                    // 存入session
                    ctx.commit('setUserInfo', res.data.userInfo)
                } else {
                    alert(res.msg)
                }
            })
        },
        // 注销
        async logout(ctx, Router) {
            ctx.commit("setUserInfo", {})
        }
    }
})
